package com.foreknow.example8;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Test5 {
    public static void main(String[] args) {
        try {
            // 读取文本文件
            BufferedReader reader = new BufferedReader(new FileReader("student.txt"));
            String line;
            Map<String, Integer> wordCountMap = new HashMap<>();

            // 统计单词出现次数
            while ((line = reader.readLine()) != null) {
                String[] words = line.split("\\s+"); // 使用空格分隔单词
                for (String word : words) {
                    wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
                }
            }

            // 按照出现次数从高到低进行排序
            List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(wordCountMap.entrySet());
            sortedEntries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));

            // 打印结果
            for (Map.Entry<String, Integer> entry : sortedEntries) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }

            // 关闭文件
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
